/*
 * @Description: 全局过滤器
 * @Author: 0001100986/LiuShuai
 * @Date: 2021-09-22 14:00:25
 * @LastEditTime: 2023-08-23 09:39:59
 * @LastEditors: 0001100986/LiuShuai
 */

// 软件SN过滤
const filterSN = (val) => {
  if (val === '' || val === null || val === undefined) {
    return '';
  } else {
    // 转换数组
    let mac = val.split(':');
    for (let i = 0; i < mac.length; i++) {
      if (i === 0) {
        if (mac[i].length === 2) {
          // eslint-disable-next-line no-self-assign
          mac[i] = mac[i];
        } else {
          mac[i] = '0' + mac[i];
        }
      } else {
        if (mac[i].indexOf(' ') === 0) {
          mac[i] = '0' + mac[i].substring(1, mac[i].length);
        }
      }
    }
    mac = mac.join(':');
    return mac;
  }
};

// 隐藏姓名 示例：张三 》 张*
const hideName = (name) => {
  // 存放名字中间的*
  if (name) {
    let star = '';
    // 名字是两位的就取姓名首位+*
    if (name.length <= 2) {
      return name.substring(0, 1) + '*';
    } else {
      for (let i = 0; i < name.length - 2; i++) {
        star = star + '*';
      }
      return name.substring(0, 1) + star + name.substring(name.length - 1, name.length);
    }
  }
};

// 隐藏用户手机号中间四位 示例：18155731998 》 181****1998
const hidePhone = (phone) => {
  // 过滤空值
  if (phone) {
    return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
  }
};

// 隐藏邮箱 示例：lz17054752@zte.com.cn 》 lz1******@zte.com.cn
const hideEmail = (email) => {
  // 匹配邮箱
  if (String(email).indexOf('@') > 0) {
    let new_email;
    let str = email.split('@');
    let _s = '';
    if (str[0].length > 3) {
      for (let i = 0; i < str[0].length - 3; i++) {
        _s += '*';
      }
    }
    new_email = str[0].substr(0, 3) + _s + '@' + str[1];
    return new_email;
  }
};

// 隐藏IP 区分IPv4 / IPv6 示例：192.168.0.42 》 192.-----.42   00:11:02:03:04:06 》 00:-----------:06
const hideIp = (ip) => {
  // 过滤空值
  if (ip) {
    // IPv4
    if (ip.indexOf('.') > 0) {
      const result = hideStr(ip, ip.indexOf('.') + 1, ip.length - ip.lastIndexOf('.'), '-');
      return result;
    } else {
      // IPv6
      const result = hideStr(ip, ip.indexOf(':') + 1, ip.length - ip.lastIndexOf(':'), '-');
      return result;
    }
  }
};


// 统一敏感信息隐藏 str 需要处理的字符串  frontLen  保留的前几位 endLen  保留的后几位 char  替换的字符串
const hideStr = (str, frontLen, endLen, char) => {
  let len = str.length - frontLen - endLen;
  let midStr = '';
  for (let i = 0; i < len; i++) {
    midStr += char;
  }
  let leftStr = str.substring(0, frontLen);
  let rightStr = str.substring(str.length - endLen);
  let newStr = leftStr + midStr + rightStr;
  return newStr;
};

export default { filterSN, hideName, hidePhone, hideEmail, hideIp };